<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use think\Db;
use service\ToolsService;
use think\exception\HttpResponseException;
/**
 * 订单管理
 */
class Order extends BasicAdmin
{

    /**
     * 定义当前操作表名
     * @var string
     */
    public $order = 'jixie_order';
    public $order_goods = 'jixie_order_goods';
    public $member = 'jixie_member';
    public $member_address = 'jixie_member_address';
    public $member_express = 'jixie_express';
    public $agent = 'jixie_agent';

    /**
     * 订单列表
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $this->title = '订单管理';
        $db = Db::name($this->order);
        $get = $this->request->get();

        // =============== 主订单过滤 ===============
        foreach (['order_no', 'pay_status', 'delivery_status'] as $field) {
            (isset($get[$field]) && $get[$field] !== '') && $db->whereLike($field, "%{$get[$field]}%");
        }
        (isset($get['order_status']) && $get['order_status'] !== '') && $db->where('order_status', $get['order_status']);

        // 订单时间过滤
        foreach (['create_at', 'pay_time'] as $field) {
            if (isset($get[$field]) && $get[$field] !== '') {
                list($start, $end) = explode(' - ', $get[$field]);
                $db->whereBetween($field, ["{$start} 00:00:00", "{$end} 23:59:59"]);
            }
        }
        return parent::_list($db->order('order_id desc'));
    }

    /**
     * 订单列表数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _data_filter(&$data)
    {
        $this->buildOrderList($data);
    }

    public function buildOrderList(&$list)
    {
        $mids = array_unique(array_column($list, 'member_id'));
        $orderNos = array_unique(array_column($list, 'order_id'));
        $addressNos = array_unique(array_column($list, 'address_id'));
        $expressNos = array_unique(array_column($list, 'express_id'));
        $agentNos = array_unique(array_column($list, 'agent_id'));
        $memberList = Db::name($this->member)->whereIn('member_id', $mids)->select();
        $goodsList = Db::name($this->order_goods)->whereIn('order_id', $orderNos)->select();
        $addressList = Db::name($this->member_address)->whereIn('address_id', $addressNos)->select();
        $expressList = Db::name($this->member_express)->whereIn('express_id', $expressNos)->select();
        $agentList = Db::name($this->agent)->whereIn('agent_id', $agentNos)->select();
        foreach ($list as $key => $vo) {
            list($list[$key]['member'], $list[$key]['goods'], $list[$key]['address'], $list[$key]['express'], $list[$key]['agent']) = [[], [], [], [], []];
            foreach ($memberList as $member) {
                $member['nick_name'] = ToolsService::emojiDecode($member['nick_name']);
                ($vo['member_id'] === $member['member_id']) && $list[$key]['member'] = $member;
            }
            foreach ($expressList as $express) {
                ($vo['express_id'] === $express['express_id']) && $list[$key]['express'] = $express;
            }

            foreach ($addressList as $address) {
                ($vo['address_id'] === $address['address_id']) && $list[$key]['address'] = $address;
            }
            foreach ($goodsList as $goods) {
                ($vo['order_id'] === $goods['order_id']) && $list[$key]['goods'][] = $goods;
            }
            foreach ($agentList as $agent) {
                ($vo['agent_id'] === $agent['agent_id']) && $list[$key]['agent'] = $agent;
            }
        }
        return $list;
    }

    /**
     * 订单地址修改
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function address()
    {
        $address_id = $this->request->get('id');
        if ($this->request->isGet()) {
            $orderExpress = Db::name($this->member_address)->where(['address_id' => $address_id])->find();
            empty($orderExpress) && $this->error('该订单无法进行地址修改！');
            return $this->fetch('', $orderExpress);
        }
        $data = [
            'address_id' => $address_id,
            'name' => $this->request->post('express_username'),
            'mobile' => $this->request->post('express_phone'),
            'detail' => $this->request->post('express_desc'),
        ];
        if (DataService::save($this->member_address, $data, 'address_id')) {
            $this->success('收货地址修改成功！', '');
        }
        $this->error('收货地址修改失败，请稍候再试！');
    }

    /**
     * 发货
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function delivery()
    {
        if (!$this->request->isPost()) {
            $order_id = $this->request->get('id');
            $order = Db::name($this->order)->find($order_id);
            empty($order) && $this->error('未找到相关订单！');
            $this->_form_assign();
            return $this->fetch('form', ['vo' => $order, 'title' => '发货']);
        }
        try {
            $order_id = $this->request->post('id');
            $order = Db::name($this->order)->find($order_id);
            empty($order) && $this->error('未找到相关订单！');

            $data = [
                'delivery_status' => 1,
                'delivery_time' => date('Y-m-d H:i:s', time()),
                'express_id' => $this->request->post('express_id'),
                'express_no' => $this->request->post('express_no'),
            ];

            Db::transaction(function () use ($data, $order_id, $order) {
                $where = ['order_id' => $order_id, 'delivery_status' => '0'];
                Db::name($this->order)->where($where)->update($data);

            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('发货失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('发货成功！', "");
    }

    /**
     * 表单数据处理
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _form_assign()
    {
        list($where, $order) = [[], 'sort_order desc'];
        $express = (array)Db::name($this->member_express)->where($where)->order($order)->select();
        $this->assign([
            'express' => $express,
        ]);
    }

    /**
     * 订单信息API
     * @return array|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function infoApi()
    {
        $id = $this->request->post('id');
        $vo = Db::name($this->order)->where(['order_no' => $id])->find();
        if (empty($vo)) {
            return json(['code' => 1, 'message' => '订单不存在', 'data' => '']);
        } else {
            return json(['code' => 0, 'message' => '订单数据', 'data' => $vo]);
        }

    }

}
